package com.pug.security.rest;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.pug.security.dto.UserLoginReqDTO;
import com.pug.security.service.impl.UserLoginServiceImpl;
import com.pug.security.vo.UserDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xq.pug.common.result.R;

import java.util.HashMap;
import java.util.Map;

/**
 * @author RenGaoshuai
 * @date 2023/7/19 9:36
 * @description
 */
@RestController
@RequestMapping("/login")
@Slf4j
public class UserLoginController {

    @Autowired
    private UserLoginServiceImpl userLoginService;
    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/getToken")
    public R<String> getToken(@RequestBody UserLoginReqDTO dto) {
        log.info("进入登录方法，准备获取token");
        Authentication authenticate;
        try {
            //这里就是去校验用户名密码的，它会走到我们自定义的那个业务类里面
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword());
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (BadCredentialsException e) {
            return R.ofFail("账号或密码错误");
        }
        //获取到查询出来的用户
        UserDetailVO userDetailVO = (UserDetailVO) authenticate.getPrincipal();

        //获取token
        String token = userLoginService.getUserToken(userDetailVO);
        log.info("退出登录方法，成功获取token");
        return R.ofSuccess(token);
    }


}
